package dao.manager.impl;

import dao.BaseDao;
import dao.manager.ReturnDao;
import entity.Borrow_books;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * ReturnDaoImpl
 *
 * @author ChenYanMei
 * @version 2023/8/31
 */
public class ReturnDaoImpl extends BaseDao implements ReturnDao {
    /**
     * 查询逾期天数
     *
     * @param book_id 查询的书籍编号
     * @return 逾期天数
     */
    @Override
    public int overDate(int book_id) {

        Connection conn = super.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int row = 0;

        String sql = "select DATEDIFF(end_date, NOW()) AS over_days from borrow_books where return_date is null and book_id=?";

        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, book_id);
            rs=pstmt.executeQuery();
            while (rs.next()){
                row = rs.getInt("over_days");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    /**
     * 查询全部信息
     *
     * @param book_id
     * @return
     */
    @Override
    public Borrow_books selectAll(int book_id) {
        Borrow_books borrow_books = new Borrow_books();

        Connection conn = super.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        String sql = "select * from borrow_books where return_date is null and = book_id=?";

        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, book_id);
            rs=pstmt.executeQuery();
            while (rs.next()){
                borrow_books.setId(rs.getInt("id"));
                borrow_books.setCard_id(rs.getInt("card_id"));
                borrow_books.setBook_id(rs.getInt("book_id"));
                borrow_books.setBorrow_date(rs.getString("borrow_date"));
                borrow_books.setEnd_date(rs.getString("end_date"));
                borrow_books.setReturn_date(rs.getString("return_date"));
                borrow_books.setIllegal(rs.getString("illegal"));
                borrow_books.setManager_id(rs.getString("manager_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            super.closeAll(rs, pstmt, conn);
        }
        return borrow_books;
    }
}
